package com.blrs.controller;

import com.blrs.common.core.controller.BaseController;
import com.blrs.common.core.domain.AjaxResult;
import com.blrs.domain.DimIndustry;
import com.blrs.service.dimlndustry.IDimIndustryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 行业维度信息 控制层
 */
@RestController
@RequestMapping("/system/industry")
public class DimIndustryController extends BaseController {
    
    private static final String INDUSTRY_TREE_KEY = "industry:tree";
    
    private static final Logger log = LoggerFactory.getLogger(DimIndustryController.class);
    
    @Autowired
    private IDimIndustryService dimIndustryService;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取行业树形数据
     */
    @GetMapping("/tree")
    public AjaxResult getIndustryTree() {
        try {
            // 先从Redis获取
            List<DimIndustry> cacheTree = (List<DimIndustry>) redisTemplate.opsForValue().get(INDUSTRY_TREE_KEY);
            if (cacheTree != null) {
                log.info("从Redis获取行业树数据，大小：{}", cacheTree.size());
                return AjaxResult.success(cacheTree);
            }

            // Redis没有，从数据库获取并缓存
            List<DimIndustry> list = dimIndustryService.selectIndustryTree();
            log.info("从数据库获取行业树数据，大小：{}", list != null ? list.size() : 0);

            if (list != null && !list.isEmpty()) {
                redisTemplate.opsForValue().set(INDUSTRY_TREE_KEY, list, 24, TimeUnit.HOURS);
                return AjaxResult.success(list);
            }
            
            return AjaxResult.success(Collections.emptyList());
        } catch (Exception e) {
            log.error("获取行业树失败", e);
            return AjaxResult.error("获取行业树失败：" + e.getMessage());
        }
    }

    /**
     * 根据行业ID获取行业信息
     */
    @GetMapping("/{industryId}")
    public AjaxResult getIndustryById(@PathVariable String industryId) {
        try {
            DimIndustry industry = dimIndustryService.selectIndustryById(industryId);
            return AjaxResult.success(industry);
        } catch (Exception e) {
            return AjaxResult.error("获取行业信息失败：" + e.getMessage());
        }
    }
} 